const request=require('request');
const base='http://localhost:5000';

const postNew=()=>new Promise((resolve,reject)=>{
    request.post(base+'/new',(err,res,body)=>{
        if(err)return reject(err);
        try{
            body=JSON.parse(body);
        }catch(err){
            if(err)return reject(err);
        }
        resolve(body);
    });
}).catch(err=>{
    console.error('postNew-ERROR:\n',err);
    throw err;
});

const getChildrenIds=(treeId,rootId)=>new Promise((resolve,reject)=>{
    let uri=`${base}/${treeId}/children/${rootId}`;
    request.get(uri,(err,res,body)=>{
        if(err)return reject(err);
        try{
            body=JSON.parse(body);
        }catch(err){
            throw err;
        }
        resolve(body);
    });
});

const createTree=async (treeId,rootId)=>{
    let ids=await  getChildrenIds(treeId,rootId);
    let children=await Promise.all(ids.map(cid=>new Promise(resolve=>{
        setTimeout(()=>{
            resolve(createTree(treeId,cid));
        },50);
    })));
    return {id:rootId,children};
};


const check=async (treeId,tree)=>new Promise((resolve)=>{
    request.post(`${base}/${treeId}/check`,{form:{root:JSON.stringify(tree)}},(err,res,body)=>{
        if(err)throw err;
        resolve(body);
    });
});

(async ()=>{
    let newRet=await postNew();
    console.log('newRet:',newRet);

    let tree=await createTree(newRet.id,newRet.rootId);

    console.log('createTree:\n',JSON.stringify(tree));

    let ret=await check(newRet.id,tree);

    console.log('check ret:',ret);
})();
